﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace weba.Sales
{
    public partial class PurchaseOrderDetailArrivalManage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (Request.QueryString["PurchaseOrderID"] != null)
                {
                    if (mk.IsNumber(Request.QueryString["PurchaseOrderID"].ToString()))
                    {
                        //用一个隐藏Label保存传递过来的ID
                        this.lblPurchaseOrderID.Text = Request.QueryString["PurchaseOrderID"].ToString();
                    }
                    else
                    {
                        mk.Alert("参数错误！");
                    }
                }
                else
                {
                    mk.Alert("参数错误！");
                }

                //绑定页面基本数据
                this.BindData();
            }
        }
        private void BindData()
        {
         var bllHeader = mk.l.Sales_PurchaseOrderHeader.ToList();
   Sales_PurchaseOrderHeader mHeader = bllHeader.Where(h=>h.PurchaseOrderID==int.Parse(this.lblPurchaseOrderID.Text)).FirstOrDefault();
            if (mHeader != null)
            {
            Accounts_Users currentUser = mk.l.Accounts_Users.FirstOrDefault();
                //设置根部门ID
                var bllDept = mk.l.Accounts_Department.ToList();
                 this.lblRootDepartmentID.Text = bllDept.Where(j=>j.ClassID==(int.Parse(currentUser.DepartmentID))).FirstOrDefault().RootID.ToString();
                if (int.Parse(this.lblRootDepartmentID.Text) == mHeader.RootDepartmentID)
                {
                    //设置入库经办人
                    this.lblInventoryManager.Text = currentUser.UserName;
                    //显示厂家名称
               var bllM = mk.l.Sales_Manufacturer.ToList();
                  Sales_Manufacturer mM = bllM.Where(h=>h.ManufacturerID==mHeader.ManufacturerID).FirstOrDefault();
                    this.lblManufacturerName.Text = mM.ManufacturerName;
                    this.lblOrderNumber.Text = mHeader.OrderNumber;
                    this.lblDateOrder.Text = mHeader.DateOrder.ToString();
                    //显示订货人姓名
                   var bllUser = mk.l.Accounts_Users.ToList();
                   Accounts_Users mUser = bllUser.Where(h => h.UserName==mHeader.Manager).FirstOrDefault();
                    this.lblManagerTrueName.Text = mUser.TrueName;
                    //this.lblSubTotal.Text = mHeader.SubTotal.ToString("c");
                    this.BindPurchaseOrderDetail();
                    //绑定仓库下拉列表框
                    this.BindLocationID(ddlLocationID);
                    //不能修改已经到货的订单
                    //判断是否是本人添加的订单，不能修改别人添加的订单
                    if (mHeader.StatusArrival == "1")
                    {
                        this.btnOK.Enabled = false;
                        this.btnOK.Visible = false;
                        this.btnSelectInInventory.Enabled = false;
                        this.btnSelectInInventory.Visible = false;
                        this.btnClose.Enabled = true;
                        this.btnClose.Visible = true;
                        this.myGridView.Columns[6].Visible = false;
                    }
                }
                else
                {
                   mk.Alert("只能操作本店的订单！");
                }
            }
            else
            {
               mk.Alert("参数错误！");
            }

        }

        /// <summary>
        /// Binds the purchase order detail.
        /// </summary>
        private void BindPurchaseOrderDetail()
        {
            var bll = mk.l.Sales_MaterialandSales_PurchaseOrderDetail.ToList();
        var ds = bll.Where(y=>y.PurchaseOrderID.ToString()== this.lblPurchaseOrderID.Text);
            this.myGridView.DataSource = ds;
            this.myGridView.DataBind();
        }

        /// <summary>
        /// Handles the RowEditing event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewEditEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.myGridView.EditIndex = e.NewEditIndex;
            this.BindPurchaseOrderDetail();
        }

        /// <summary>
        /// Handles the RowCancelingEdit event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewCancelEditEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            this.myGridView.EditIndex = -1;
            this.BindPurchaseOrderDetail();
        }

        /// <summary>
        /// Handles the RowUpdating event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewUpdateEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            if (this.IsValid)
            {
                this.lblMsg.Text = "";  
                //得到用户选择仓库位置的DropDownList控件
                DropDownList ddlLocationID = 
                    (DropDownList)(this.myGridView.Rows
                    [e.RowIndex].FindControl("ddlLocationID"));
                //得到订货单详细材料ID
                int intDetailID = 
                    int.Parse(this.myGridView.DataKeys
                    [e.RowIndex].Values["DetailID"].ToString());
                //获取用户在DropDownList中选择的仓库位置
                int intLocationID = int.Parse(ddlLocationID.SelectedValue);
                //获取订货单明细对象实例
              var bll = 
                   mk.l.Sales_PurchaseOrderDetail.ToList();
                Sales_PurchaseOrderDetail m = 
                    bll.Where(h=>h.DetailID==intDetailID).FirstOrDefault();
                //如果已经入库则跳过不计
               
                if (m.StatusArrival == "0")
                {
                    int intMaterialID = int.Parse(m.MaterialID.ToString());
                    decimal decQuantity =Convert.ToDecimal( m.Quantity.ToString());
                    //保存原仓库ID
                    int intOldLocationID = int.Parse(m.LocationID.ToString());                    
                    //为订货单明细赋材料入库信息
                    m.StatusArrival = "1"; 
                    m.InventoryManager = this.lblInventoryManager.Text;
                    m.LocationID =short.Parse( intLocationID.ToString()) ;
                    m.DateArrival = System.DateTime.Now;
                    m.ModifiedDate = System.DateTime.Now;
                    //这里要用事务，更新记录，同时更新订货单概况的信息
                    try
                    {
                       mk.l.SubmitChanges();
                       var bllHeader = mk.l.Sales_PurchaseOrderHeader.ToList();
                        //    new UART.BLL.Sales.PurchaseOrderHeader();
                        //如果此订货单已全部到货，设置订货单到货状态
                        if (mk.IsAllArrival(int.Parse(this.lblPurchaseOrderID.Text)))
                        {
                            //更新订货单表头的到货状态
                           Sales_PurchaseOrderHeader mHeader = 
                                bllHeader.Where(h=>h.PurchaseOrderID==int.Parse(this.lblPurchaseOrderID.Text)).FirstOrDefault();
                            mHeader.StatusArrival = "1";
                            mHeader.ModifiedDate = System.DateTime.Now;
                           // bllHeader.Update(mHeader);
                            mk.l.SubmitChanges();
                        }
                        //材料入库 修改库存
                      var bllInventory = 
                           mk.l.Sales_MaterialInventory.ToList();
                        //先判断是否修改了入库仓库，如果修改了则以前的仓库要出库，再向新仓库入库
                        if (intOldLocationID != 0 && intOldLocationID != intLocationID)
                        {
                            //处理出库操作
                           mk.StockOut(intMaterialID, decQuantity, intOldLocationID, 
                                int.Parse(this.lblRootDepartmentID.Text));
                        }
                        //处理入库操作
                       mk.StockIn(intMaterialID, decQuantity, 
                            intLocationID, int.Parse(this.lblRootDepartmentID.Text));
                        //提交事务
                      //  ContextUtil.SetComplete();
                    }
                    catch (Exception ex)
                    {

                      //  ContextUtil.SetAbort();   //撤销事务
                        this.lblMsg.Text = "入库错误！错误信息：" + ex.Message;
                    }
                }
                this.myGridView.EditIndex = -1;
                this.BindPurchaseOrderDetail();  //重新绑定材料明细
            }
        }

        /// <summary>
        /// Handles the RowDataBound event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
               var bll = mk.l.Sales_PurchaseOrderDetail.ToList();
         Sales_PurchaseOrderDetail  m = bll.Where(h=>h.DetailID==int.Parse(this.myGridView.DataKeys[e.Row.RowIndex].Values["DetailID"].ToString())).FirstOrDefault();

                //显示是否到货 仓库信息
                if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
                {
                    Label lblLocation = (Label)(e.Row.FindControl("lblLocation"));
                    Label lblStatusArrival = (Label)(e.Row.FindControl("lblStatusArrival"));

                    if (lblLocation != null)
                    {
                        if (m.LocationID == 0)
                        {
                            lblLocation.Text = "未入库";
                            lblLocation.ForeColor = System.Drawing.Color.Red;
                        }
                        else
                        {
                            var bllLocation = mk.l.Sales_Location.ToList();
                           Sales_Location mLocation = bllLocation.Where(h=>h.LocationID==m.LocationID).FirstOrDefault();
                            lblLocation.Text = mLocation.Name;
                            lblLocation.ForeColor = System.Drawing.Color.Green;
                        }
                    }
                    if (lblStatusArrival != null)
                    {
                        if (m.StatusArrival == "0")
                        {
                            lblStatusArrival.Text = "未到货";
                            lblStatusArrival.ForeColor = System.Drawing.Color.Red;
                        }
                        else
                        {
                            lblStatusArrival.Text = "已入库";
                            lblStatusArrival.ForeColor = System.Drawing.Color.Green;
                        }
                    }
                }
                if (e.Row.RowState == DataControlRowState.Edit || (int)e.Row.RowState == 5)
                {
                    DropDownList ddlLocationID = (DropDownList)(e.Row.FindControl("ddlLocationID"));
                    this.BindLocationID(ddlLocationID);
                    if (m.LocationID != 0)
                    {
                        ddlLocationID.Items.FindByValue(m.LocationID.ToString()).Selected = true;
                    }
                }
                
            }
        }

        /// <summary>
        /// Binds the location ID.绑定指定的仓库下拉列表框
        /// </summary>
        /// <param name="ddlLocationID">The DDL location ID.</param>
        private void BindLocationID(DropDownList ddlLocationID)
        {
           var  bll = mk.l.Sales_Location.ToList();
          var ds = bll.Where(y=>y.RootDepartmentID.ToString()==this.lblRootDepartmentID.Text);
            ddlLocationID.DataSource = ds;
            ddlLocationID.DataTextField = "Name";
            ddlLocationID.DataValueField = "LocationID";
            ddlLocationID.DataBind();
        }



        /// <summary>
        /// Handles the Click event of the btnSelectInInventory control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnSelectInInventory_Click(object sender, EventArgs e)
        {
            if (this.IsValid)
            {
                string strArrDetailID = string.Empty;
                //遍历所有的 chkSelect 
                foreach (GridViewRow gr in this.myGridView.Rows)
                {
                    CheckBox chk = (CheckBox)gr.FindControl("chkSelect");
                    if (chk.Checked)
                    {
                        strArrDetailID = strArrDetailID + this.myGridView.DataKeys[gr.RowIndex].Values["DetailID"].ToString() + ",";
                    }
                }
                if (strArrDetailID != string.Empty)
                {
                    strArrDetailID = strArrDetailID.Substring(0, strArrDetailID.Length - 1);
                    string[] arrDetailID = strArrDetailID.Split(',');
                    int intLocationID = int.Parse(this.ddlLocationID.SelectedValue);
                    //这里要用事务，更新记录，同时更新订货单概况的信息
                    try
                    {
                        for (int i = 0; i < arrDetailID.Length; i++)
                        {
                            int intDetailID = int.Parse(arrDetailID[i]);
                    var bll = mk.l.Sales_PurchaseOrderDetail.ToList();
                          Sales_PurchaseOrderDetail m = bll.Where(h=>h.DetailID==intDetailID).FirstOrDefault();
                            //这里要判断一下，如果已经入库，就不处理了
                            if (m.StatusArrival == "0")
                            {
                                int intMaterialID =int.Parse( m.MaterialID.ToString());
                                decimal decQuantity =Convert.ToDecimal( m.Quantity.ToString());
                                //保存原仓库ID
                                int intOldLocationID =int.Parse( m.LocationID.ToString());
                                //材料入库
                                m.StatusArrival = "1";
                                m.InventoryManager = this.lblInventoryManager.Text;
                                m.LocationID =short.Parse( intLocationID.ToString());
                                m.DateArrival = System.DateTime.Now;
                                m.ModifiedDate = System.DateTime.Now;

                              //  bll.Update(m);
                                mk.l.SubmitChanges();
                                //材料入库 修改库存
                             //   UART.BLL.Sales.MaterialInventory bllInventory = new UART.BLL.Sales.MaterialInventory();
                                //先判断是否修改了入库仓库，如果修改了，则以前的仓库要出库，再向新仓库入库
                                if (intOldLocationID != 0 && intOldLocationID != intLocationID)
                                {
                                   mk.StockOut(intMaterialID, decQuantity, intOldLocationID, int.Parse(this.lblRootDepartmentID.Text));
                                }
                            mk.StockIn(intMaterialID, decQuantity, intLocationID, int.Parse(this.lblRootDepartmentID.Text));
                                //this.myGridView.EditIndex = -1;
                            }
                        }

                        var bllHeader = mk.l.Sales_PurchaseOrderHeader.ToList();
                        //如果此订货单已全部到货，设置订货单到货状态
                        if (mk.IsAllArrival(int.Parse(this.lblPurchaseOrderID.Text)))
                        {
                          Sales_PurchaseOrderHeader mHeader = bllHeader.Where(h=>h.PurchaseOrderID==int.Parse(this.lblPurchaseOrderID.Text)).FirstOrDefault();
                            mHeader.StatusArrival = "1";
                            mHeader.ModifiedDate = System.DateTime.Now;
                           // bllHeader.Update(mHeader);
                            mk.l.SubmitChanges();
                        }
                        this.btnSelectInInventory.Enabled = false;
                        this.lblMsg.Text = "入库成功！";
                        //提交事务
                      //  ContextUtil.SetComplete();
                    }
                    catch (Exception ex)
                    {
                        //撤销事务
                      //  ContextUtil.SetAbort();
                        this.lblMsg.Text = "入库错误！错误信息：" + ex.Message;
                    }

                }
                this.BindPurchaseOrderDetail();
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {

        }


    }
}
